<template>
  <div
    class="examine-detail-container animate__animated"
    :class="[visible ? 'animate__fadeIn' : 'animate__fadeOut']"
  >
    <div class="page-modal-container">
      <div class="page-modal-body">
        <div class="card-container">
          <div class="statistics-card">
            <div class="icon"></div>
            <div class="score">
              <div class="total">
                {{ totalData.allCount || 0 }}<span>个</span>
              </div>
              <div class="tip">指标项总数</div>
            </div>
          </div>
          <div class="statistics-card">
            <div class="icon"></div>
            <div class="score">
              <div class="total">
                {{ totalData.ywcCount || 0 }}<span>个</span>
              </div>
              <div class="tip">已完成指标项数</div>
            </div>
          </div>
          <div class="statistics-card">
            <div class="icon"></div>
            <div class="score">
              <div class="total">
                {{ totalData.wwcCount || 0 }}<span>个</span>
              </div>
              <div class="tip">未完成指标项数</div>
            </div>
          </div>
          <div class="statistics-card">
            <div class="icon"></div>
            <div class="score">
              <div class="total">
                {{ totalData.finalScore || 0 }}<span>分</span>
              </div>
              <div class="tip">专家评分</div>
            </div>
          </div>
          <div class="statistics-card">
            <div class="icon"></div>
            <div class="score">
              <div class="total">
                {{ totalData.totalScore || 0 }}<span>分</span>
              </div>
              <div class="tip">总分</div>
            </div>
          </div>
        </div>
        <div class="body-container">
          <div class="tree-container">
            <div class="button-group">
              <div
                class="button"
                :class="{ checked: dealSatus == '' }"
                @click="checkDealSatus('')"
              >
                全部
              </div>
              <div
                class="button"
                :class="{ checked: dealSatus == '4' }"
                @click="checkDealSatus('4')"
              >
                已完成
              </div>
              <div
                class="button"
                :class="{ checked: dealSatus == '2' }"
                @click="checkDealSatus('2')"
              >
                未完成
              </div>
            </div>
            <div class="search">
              <a-input-search
                v-model.trim="keyWord"
                @search="filterTreeData()"
                style="width: 100%"
                placeholder="请输入关键词"
              />
            </div>
            <div class="tree-data">
              <a-empty v-if="treeData.length == 0" />
              <a-tree
                v-if="treeData.length > 0 && treeShow"
                show-icon
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :tree-data="treeData"
                :replaceFields="{
                  children: 'childs',
                  title: 'evaluationName',
                  key: 'uuid',
                }"
                @expand="onExpand"
                @select="onSelect"
              >
                <template
                  slot="title"
                  slot-scope="{ evaluationName, totalScore, finalScore }"
                >
                  <div class="custom-tree-item flex" :title="evaluationName">
                    <div class="label">{{ evaluationName }}</div>
                    <div class="value">
                      {{ finalScore }}<span>/{{ totalScore }}分</span>
                    </div>
                  </div>
                </template>
                <!-- 文件夹图标 -->
                <template slot="custom" slot-scope="{ expanded, childs }">
                  <a-icon
                    :type="
                      childs && childs.length > 0
                        ? expanded
                          ? 'folder-open'
                          : 'folder'
                        : 'file'
                    "
                    :class="
                      childs && childs.length > 0 ? 'folder-icon' : 'file-icon'
                    "
                  />
                </template>
              </a-tree>
            </div>
          </div>
          <div class="data-container">
            <vxe-table
              ref="xTable"
              align="center"
              show-overflow
              show-header-overflow
              border="inner"
              height="524"
              :data="tableData"
              :column-config="{ resizable: true }"
              size="small"
              :loading="tableLoading"
            >
              <vxe-column type="seq" width="80" title="序号"></vxe-column>
              <vxe-column
                field="assessmentContent"
                title="五级指标"
              ></vxe-column>
              <vxe-column field="determine" title="判定标准"> </vxe-column>
              <vxe-column field="orgName" title="责任主体"></vxe-column>
              <vxe-column title="专家评分/自评分/总分（分）">
                <template #default="{ row }">
                  <span style="color: #3759a0">
                    {{ row.finalScore || "-" }}
                  </span>
                  /{{ row.ownScore || "-" }}/{{ row.singleScore || "-" }}
                </template>
              </vxe-column>
              <vxe-column field="statusDesc" title="状态" width="100">
                <template #default="{ row }">
                  <span class="table-td" :class="getClassName(row.statusDesc)">
                    {{ row.statusDesc }}
                  </span>
                </template>
              </vxe-column>
              <vxe-column field="khStartDate" title="考核开始时间" width="100">
              </vxe-column>
              <vxe-column field="khEndDate" title="考核结束时间" width="100">
              </vxe-column>
              <vxe-column
                field="operate"
                width="80"
                title="操作"
                fixed="right"
                align="left"
              >
                <template #default="{ row }">
                  <div class="text-button-group">
                    <a-button type="link" @click="viewDetail(row)">
                      查看
                    </a-button>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </div>
    </div>
    <detailModal
      :visible.sync="detailModalVisible"
      :soucre="dataSoucre"
      @cancel="detailCancel()"
    ></detailModal>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
import { addAttributeByKey, getNodeByKey } from "@/utils/index.js";
import { flatTreeData } from "@/utils/util";
import detailModal from "./detailModal";
export default {
  components: {
    detailModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    treeItem: {
      type: Object,
      default: () => {
        return {};
      },
    },
    dataType: {
      type: String,
      default: "",
    },
    soucre: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      //标段
      orgCode: undefined,
      blockLoading: false,
      blockNameSource: [],
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      keyWord: "",
      pager: {
        page: 1,
        pageSize: 999,
        total: 0,
      },
      tableLoading: false,
      orgCode: undefined,
      orgCodeLoading: false,
      orgCodeSource: [],
      loading: false,
      totalData: {},
      dealSatus: "",
      currentNode: {},
      treeShow: false,
      pageParams: {},
      expertData: {},
      tableData: [],
      detailModalVisible: false,
      dataSoucre: {},
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    detailCancel() {
      this.detailModalVisible = false;
      this.getData();
    },
    //查看
    viewDetail(row) {
      let { orgCode = "" } = this;
      let { tenantCode } = this.$parent;
      this.detailModalVisible = true;
      this.dataSoucre = {
        orgCode,
        tenantCode,
        id: row.uuid,
        statusDesc: row.statusDesc,
      };
    },

    //查询数据
    getData() {
      Promise.all([
        this.getDepartmentList(),
        this.getTotalData(),
        this.getTreeData(),
      ])
        .then()
        .finally((_) => {});
    },
    //查询标段
    getDepartmentList() {
      this.blockLoading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode = "" } = this.$parent;
        axios
          .get(
            `/mdata/sysOrgExtend/getOrgExtendListByQX?tenantCode=${tenantCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.blockNameSource = res?.data || [];
            resolve();
          })
          .catch((_) => {
            this.blockNameSource = [];
            reject();
          })
          .finally((_) => {
            this.blockLoading = false;
          });
      });
    },

    search() {
      this.getTotalData();
      this.getTreeData().then((res) => {
        this.getTableSource();
      });
    },

    //查询统计数据
    getTotalData(code = "") {
      this.loading = false;
      let { orgCode = "" } = this;
      let { tenantCode } = this.$parent;
      return new Promise((resolve, reject) => {
        axios
          .get(
            `/probusiness/qeStatistics/getTotalData?orgCode=${code ||
              (orgCode ?? "")}&tenantCode=${tenantCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.totalData = res?.data || {};
            resolve();
          })
          .catch((_) => {
            this.totalData = {};
            reject();
          })
          .finally((_) => {
            this.loading = true;
          });
      });
    },

    //查询树形数据
    getTreeData() {
      let { orgCode = "", dealSatus } = this;
      let { uuid } = this.soucre;
      let { tenantCode } = this.$parent;
      return new Promise((resolve, reject) => {
        axios
          .get(
            `/probusiness/qeStatistics/getPJZBTJList?orgCode=${orgCode}&dealSatus=${dealSatus}&tenantCode=${tenantCode}`,
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let source = res?.data || [];
            this.treeData =
              addAttributeByKey(
                null,
                "scopedSlots",
                { icon: "custom" },
                source,
                "childs"
              ) || [];
            if (source.length == 0) {
              this.tableData = [];
              return;
            }
            if (uuid) {
              let nodeItem = getNodeByKey(
                uuid,
                "uuid",
                res?.data || [],
                "childs"
              );
              if (
                !nodeItem ||
                (nodeItem.childs && nodeItem.childs.length > 0)
              ) {
                this.getFirstTreeNode();
              } else {
                this.getFirstTreeNode(nodeItem);
              }
            } else {
              this.getFirstTreeNode();
            }
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.treeShow = false;
            setTimeout((_) => {
              this.treeShow = true;
            }, 100);
          });
      });
    },
    //是否是空对象
    isEmptyObject(obj) {
      return Object.keys(obj).length == 0;
    },
    //默认展开第一级节点
    getFirstTreeNode(item) {
      if (!this.currentNode || this.isEmptyObject(this.currentNode)) {
        let { treeData } = this;
        let data = {};
        let { uuid } = this.soucre;
        let flatData = flatTreeData(treeData, "childs");
        if (uuid) {
          let c = flatData.find((v) => v.uuid == uuid);
          if (!c) {
            data = flatData.find((v) => !v.childs || v.childs.length == 0);
          } else {
            data = c;
          }
        } else if (!item) {
          data = flatData.find((v) => !v.childs || v.childs.length == 0);
        } else {
          data = item;
        }
        if (data?.uuid) {
          this.expandedKeys = [data?.uuid];
          this.checkedKeys = [data?.uuid];
          this.selectedKeys = [data?.uuid];
          this.currentNode = data;
          this.getTableSource();
        } else {
          this.expandedKeys = [];
          this.checkedKeys = [];
          this.selectedKeys = [];
          this.source = [];
        }
      }
    },

    //查询考核时间
    getExaminDatwe() {
      return new Promise((resolve, reject) => {
        let { tenantCode } = this.$parent;
        axios
          .get(
            `/probusiness/qeStatistics/getExpertData?id=&tenantCode=${tenantCode}`,
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.expertData = res?.data || {};
            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询表格数据
    getTableData() {
      let { uuid } = this.currentNode;
      this.tableLoading = true;
      let { orgCode, dealSatus } = this;
      let { page, pageSize } = this.pager;
      let { tenantCode } = this.$parent;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/qeStatistics/getPJZBContentTJList?pageNo=${page}&pageSize=${pageSize}`,
            {
              tenantCode,
              orgCode,
              dealSatus,
              evaluationId: uuid,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.tableData = res.data?.rows || [];
            this.pager.total = res.data?.totalCount || 0;
            resolve();
          })
          .catch((_) => {
            this.pager.total = 0;
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.tableLoading = false;
          });
      });
    },

    //
    getTableSource() {
      Promise.all([this.getExaminDatwe(), this.getTableData()]).then(
        (result) => {
          this.tableData.forEach((v) => {
            v.khStartDate = this.expertData?.startTime ?? "-";
            v.khEndDate = this.expertData?.endTime ?? "-";
          });
          setTimeout((_) => {});
        }
      );
    },
    //切换状态
    checkDealSatus(val) {
      this.dealSatus = val || "";
      this.pager.page = 1;
      this.pager.pageSize = 999;
      this.currentNode = {};
      this.getTreeData();
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    onSelect(expandedKeys, ev) {
      let { node } = ev;
      let { uuid = "" } = node?.dataRef || {};
      this.checkedKeys = [uuid];
      this.selectedKeys = [uuid];
      this.currentNode = node?.dataRef || {};
      this.pager.page = 1;
      this.pager.pageSize = 999;
      this.getTableSource();
    },
    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableSource();
    },
    //过滤树形数据
    filterTreeData() {
      let { keyWord, treeData } = this;
      if (keyWord.trim() == "") {
        return;
      }
      let flatData = flatTreeData(treeData, "childs");
      let result = flatData.filter((v) => v.evaluationName.includes(keyWord));
      this.expandedKeys = result.map((v) => v.uuid);
      this.selectedKeys = result.map((v) => v.uuid);
      this.checkedKeys = result.map((v) => v.uuid);
    },

    getClassName(val) {
      switch (val) {
        case "待上传":
          return "dsc";

        case "已上传":
          return "ysc";

        case "待评分":
          return "dpf";

        case "已评分":
          return "ypf";

        case "已驳回":
          return "ybh";

        case "已完成":
          return "ywc";

        default:
          break;
      }
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    handelOk() {
      this.$emit("ok");
    },

    handelCancel() {
      this.$emit("cancel");
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
.examine-detail-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .page-modal-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .page-modal-body {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .card-container {
        box-sizing: border-box;
        padding: 20px 0 20px 0;
        display: flex;
        .statistics-card {
          background: @base-bg-color;
          flex: 1;
          height: 140px;
          border-radius: 6px 6px 6px 6px;
          margin-right: 20px;
          &:last-of-type {
            margin-right: 0;
          }
          display: flex;
          align-items: center;
          .icon {
            width: 72px;
            height: 72px;
            margin: 0 20px;
          }
          .score {
            .total {
              font-size: 36px;
              font-family: Microsoft YaHei, Microsoft YaHei;
              font-weight: 400;
              color: #ffffff;
              span {
                padding-left: 10px;
                font-size: 14px;
                color: rgba(255, 255, 255, 0.8);
              }
            }
            .tip {
              color: rgba(255, 255, 255, 0.8);
              font-size: 14px;
              font-family: Microsoft YaHei, Microsoft YaHei;
              font-weight: 400;
            }
          }
        }
        :nth-child(1) {
          &.statistics-card {
            background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_bg_6.png);
            background-size: 100% 100%;
            .icon {
              background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_icon_6.png);
              background-size: 100% 100%;
            }
          }
        }
        :nth-child(2) {
          &.statistics-card {
            background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_bg_7.png);
            background-size: 100% 100%;
            .icon {
              background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_icon_7.png);
              background-size: 100% 100%;
            }
          }
        }
        :nth-child(3) {
          &.statistics-card {
            background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_bg_8.png);
            background-size: 100% 100%;
            .icon {
              background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_icon_12.png);
              background-size: 100% 100%;
            }
          }
        }
        :nth-child(4) {
          &.statistics-card {
            background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_bg_1.png);
            background-size: 100% 100%;
            .icon {
              background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_icon_1.png);
              background-size: 100% 100%;
            }
          }
        }
        :nth-child(5) {
          &.statistics-card {
            background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_bg_3.png);
            background-size: 100% 100%;
            .icon {
              background: url(https://jszhgd.cn/static/pc/quality-engineering-app/card_icon_3.png);
              background-size: 100% 100%;
            }
          }
        }
      }
      .body-container {
        flex: 1;
        display: flex;
        overflow: hidden;
        .tree-container {
          display: flex;
          flex-direction: column;
          margin-right: 20px;
          width: 330px;
          flex-shrink: 0;
          border-radius: 6px 6px 6px 6px;
          overflow: hidden;
          background-color: @base-bg-color;
          .button-group {
            height: 56px;
            align-items: center;
            display: flex;
            border-bottom: 1px solid @border-color;
            font-size: 14px;
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            color: #999999;
            padding: 0 32px;
            .button {
              cursor: pointer;
              position: relative;
              letter-spacing: 2px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 40px;
              &:last-of-type {
                margin-right: 0;
              }
              &.checked {
                color: #333333;
                &::after {
                  content: "";
                  width: 20px;
                  height: 2px;
                  width: 20px;
                  height: 2px;
                  background: #1677ff;
                  border-radius: 2px 0px 2px 0px;
                  position: absolute;
                  top: 36px;
                  left: 50%;
                  transform: translateX(-50%);
                }
              }
            }
          }
          .search {
            padding: 16px 24px;
          }
          .tree-data {
            flex: 1;
            box-sizing: border-box;
            padding: 0 10px 0px 10px;
            overflow: auto;
            position: relative;
            /deep/.ant-tree {
              .ant-tree-node-content-wrapper {
                width: calc(100% - 34px);
                &.ant-tree-node-selected {
                  background: #f5f7fc !important;
                  color: @primary-color;
                }
                .folder-icon {
                  color: #f5a623;
                }
                .file-icon {
                  color: #54baff;
                }
                .ant-tree-title {
                  width: calc(100% - 24px);
                  display: inline-block;
                  .custom-tree-item {
                    width: 100%;
                    height: 100%;
                    .label {
                      flex: 1;
                      overflow: hidden;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                      margin-right: 10px;
                    }
                    .value {
                      color: #525a5d;
                      span {
                        color: @primary-color;
                      }
                    }
                  }
                }
              }
            }
            .ant-empty {
              position: absolute;
              left: 50%;
              top: 50%;
              transform: translate(-50%, -50%);
            }
          }
        }
        .data-container {
          flex: 1;
          box-sizing: border-box;
          padding: 14px;
          background-color: @base-bg-color;
        }
      }
    }
  }
}
</style>
